/*
 * @Author: Jiraiya
 * @Date: 2020-05-26 15:10:36
 * @LastEditors: Jiraiya
 * @LastEditTime: 2020-05-26 16:34:30
 * @Description: 
 */ 
const { createStore, combineReducers, applyMiddleware} = require('./redux')
const logger = require('./middlewares/logger')

function counterReducer(state, action) {
    /*如果 state 还没有值，那就给他初始值*/
    if (!state) {
      state = {
          count: 0
      };
    }
    switch (action.type) {
      case 'INCREMENT':
        return {
          ...state,
          count: state.count + 1
        }
      case 'DECREMENT':
        return {
          ...state,
          count: state.count - 1
        }
      default:
        return state;
    }
}

function infoReducer(state, action) {
    if (!state) {
      state = {
          name: '前端九部',
          description: '我们都是前端爱好者！',
      };
    }
    switch (action.type) {
      case 'SET_NAME':
        return {
          ...state,
          name: action.name
        }
      case 'SET_DESCRIPTION':
        return {
          ...state,
          description: action.description
        }
      default:
        return state;
    }
}

const reducer = combineReducers({
  counter: counterReducer,
  info: infoReducer
});

/** 
 * 注意：我们没有传 initState 进去，因为初始化的时候会执行 dispatch({ type: Symbol() });;
 * 触发 state = reducer(state, action)
 * 因为 state 为 undefined，action.type 为不匹配任何计划中 type 的值，所以会返回 reducer 中设置的默认值
 * */
/*接收旧的 createStore，返回新的 createStore*/
const rewriteCreateStoreFunc = applyMiddleware(logger);

/*返回了一个 dispatch 被重写过的 store*/
const store = createStore(reducer, {}, rewriteCreateStoreFunc);


store.subscribe(() => {
  let state = store.getState();
  console.log(state);
});

/*自增*/
store.dispatch({
  type: 'INCREMENT'
});

store.dispatch({
  type: 'SET_NAME',
  name: '前端九部2号'
});